package com.example.demo.threadCommunication;

import java.util.concurrent.TimeUnit;

/**
 * @desc: <br/>
 * @author: Jingbo Hu<br/>
 * @time：2020年07⽉01⽇<br/>
 * @version：v1.0.0<br>
 */
public class ThreadLocalDemo {

    /**
     * Synchronized用于线程间的数据共享，而ThreadLocal则用于线程间的数据隔离
     */

    private static final ThreadLocal<Long> TIME_THREADLOCAL = new ThreadLocal<Long>() {
        @Override
        protected Long initialValue() {
            return System.currentTimeMillis();
        }
    };

    public static void begin() {
        TIME_THREADLOCAL.set(System.currentTimeMillis());
    }

    public static Long end() {
        long l = System.currentTimeMillis();
        Long aLong = TIME_THREADLOCAL.get();
        return l - aLong;
    }

    public static Long get() {
        return TIME_THREADLOCAL.get();
    }

    public static void main(String[] args) throws InterruptedException {
        ThreadLocalDemo.begin();
        TimeUnit.SECONDS.sleep(3);
        System.out.println("Cost: " + ThreadLocalDemo.end() + " mills");
//        Long aLong = ThreadLocalDemo.get();
//        System.out.println(aLong);
    }
}
